﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Helpers
{
	using System;
	using System.Collections;
	using System.Web;
	using System.Web.Caching;

	public class CacheHelper
	{
		/// <summary>
		/// Gets the cache.
		/// </summary>
		/// <value>The cache.</value>
		public static Cache Cache
		{
			get
			{
				return HttpRuntime.Cache;
			}
		}

		/// <summary>
		/// Determines if a object exists in the cache.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns></returns>
		public static bool Exists(string key)
		{
			return Cache[key] != null;
		}

		/// <summary>
		/// Fetches the specified object from the cache.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns></returns>
		public static object Fetch(string key)
		{
			return Cache[key];
		}

		/// <summary>
		/// Inserts the specified object into the cache.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="value">The value.</param>
		/// <param name="expire">The expire.</param>
		public static void Insert(string key, object value, int expire)
		{
			Cache.Insert(key, value, null, DateTime.Now.AddMinutes(expire), TimeSpan.Zero);
		}

		/// <summary>
		/// Inserts the specified object into the cache for the life of the application.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="value">The value.</param>
		public static void Permanent(string key, object value)
		{
			Cache.Insert(key, value, null, DateTime.MaxValue, TimeSpan.Zero);
		}

		/// <summary>
		/// Deletes the specified object from the cache.
		/// </summary>
		/// <param name="key">The key.</param>
		public static void Delete(string key)
		{
			if (Exists(key))
			{
				Cache.Remove(key);
			}
		}

		/// <summary>
		/// Deletes all objects in the cache.
		/// </summary>
		public static void DeleteAll()
		{
			var cache = Cache.GetEnumerator();
			var list = new ArrayList();

			while (cache.MoveNext())
			{
				list.Add(cache.Key);
			}

			foreach (string key in list)
			{
				Cache.Remove(key);
			}
		}
	}
}